import uploadFile from './upload'

const {
  uploadFileUrl
} = require("./../config/config");

function uploadImage(count) {
  return new Promise((resolve, reject) => {
    wx.chooseImage({
      count: count,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: function (res) {
        const filePath = res.tempFilePaths
        resolve(filePath)
      }
    });
  })

}

//审核内容
function checkContent(content) {
  wx.showLoading({
    title: '发布中',
  })
  return new Promise((resolve, reject) => {
    wx.cloud.callFunction({
      name: 'contentCheck',
      data: {
        'content': content
      }
    }).then(res => {
      wx.hideLoading()
      console.log(res)
      //获取状态码  0 》》》正常   87014》》》违规
      const {
        errCode
      } = res.result
      if (errCode != 0) {
        wx.showToast({
          title: '提交内容含敏感词，请重新输入',
          icon: 'none'
        })
        reject()
      } else {
        resolve()
      }
    })
  })

}

function checkImg(images) {
  //上传图片到云存储
  wx.showLoading({
    title: '图片审核中',
  })
  let promiseArr = [];
  return new Promise((resolve, reject) => {
    for (var i = 0; i < images.length; i++) {
      promiseArr.push(new Promise((success, reject) => {
        let item = images[i];
        let suffix = /\.\w+$/.exec(item)[0];
        wx.cloud.uploadFile({
          cloudPath: '动态图片' + new Date().getTime() + suffix, // 上传至云端的路径
          filePath: item, // 小程序临时文件路径
          success: res => {
            wx.cloud.callFunction({
              name: 'checkImg',
              data: {
                contentType: 'image/jpg',
                fileID: res.fileID
              }
            }).then(data => {
              console.log(res, data)
              if (data.result.errCode !== 0) {
                wx.hideLoading()
                wx.showToast({
                  title: '图片内容不符合审核要求',
                  icon: 'none'
                })
                reject()
              }
              success()
            })
          },
          fail: res => {
            wx.hideLoading();
            wx.showToast({
              title: "上传失败",
            })
          }
        })
      }))
    }
    Promise.all(promiseArr).then(res => {
      wx.hideLoading();
      resolve()
    })
  })


}
//上传图片至阿里云
function uploadPic(filePath) {
  var that = this
  wx.showLoading({
    title: '上传中',
    mask: true
  })
  let suffix = /\.\w+$/.exec(filePath);
  return new Promise((resolve, reject) => {
    uploadFile(filePath, 'images/' + new Date().getTime() + suffix,
      function (result) {
        wx.hideLoading()
        resolve(result)
      },
      function (result) {
        wx.hideLoading()
        reject(result)
      }
    )
  })


}

//压缩  
const cutBase64 = (urls, canvasId, index, setCanvas, callback, type) => {

  if (index == urls.length) {
    return;
  }
  wx.showLoading({
    title: '上传中',
  })
  wx.getImageInfo({
    src: urls[index],
    success: (res) => {
      // 设置初始裁剪比例，当图片大小大于设置阈值时，则对图片长宽按次比例进行裁剪
      let ratio = 2;
      let canvasWidth = res.width;
      let canvasHeight = res.height;
      // 根据比例对图片长宽进行裁剪，若裁剪后图片大小依然大于设置阈值时，则提高裁剪比例继续对图片进行裁剪
      // 此处假定需要将图片裁剪至200kb以内，因此 阈值 = 200 * 1024 = 204800

      while (canvasWidth > 200 || canvasHeight > 200) { // 保证宽高在200以内
        canvasWidth = Math.trunc(res.width / ratio)
        canvasHeight = Math.trunc(res.height / ratio)
        ratio++;
      }
      // 调用setCanvas()方法设置canvas的长宽，设置完成后开始绘图，否则可能会出现"fail canvas is empty"的错误
      setCanvas(canvasWidth, canvasHeight, () => {
        // 获取canvasId对应的绘图上下文对象
        let ctx = wx.createCanvasContext(canvasId);
        ctx.drawImage(urls[index], 0, 0, canvasWidth, canvasHeight);
        // draw()的第一个参数为false表示不保留canvas上一次的绘制结果
        // 这里设置100毫秒的延迟是为了在canvas绘图完成后再获取图片信息，否则获取到的图片可能是空白
        ctx.draw(false, setTimeout(() => {
          // 获取canvas绘制内容并转为图片
          wx.canvasToTempFilePath({
            canvasId: canvasId,
            destWidth: canvasWidth,
            destHeight: canvasHeight,
            quality: 0.1,
            success: res => {
              // 图片导出成功后调用回调
              callback(res.tempFilePath, index, type);
              // 进行下一次递归，由于此时canvas的绘制与图片的导出都已经结束了，因此不会对canvas后续的绘制、导出产生影响
              cutBase64(urls, canvasId, ++index, setCanvas, callback);
            }
          })
        }, 100));
      });
    }
  })
  // 根据urls及index获取图片信息

}
//
function complete(filepath) {
  //上传图片到云存储
  wx.showLoading({
    title: '图片审核中',
  })
  let promiseArr = [];
  const that = this;
  let item = filepath;
  console.log(filepath)
  let suffix = /\.\w+$/.exec(item)[0]; //正则表达式返回文件的扩展名
  wx.cloud.uploadFile({
    cloudPath: '动态图片' + new Date().getTime() + suffix, // 上传至云端的路径
    filePath: item, // 小程序临时文件路径
    success: res => {
      console.log(res) //输出上传后图片的返回地址
      wx.cloud.callFunction({
        name: 'checkImg',
        data: {
          contentType: 'image/jpg',
          fileID: res.fileID
        }
      }).then(res => {
        if (res.result.errCode == 0) {
          wx.showToast({
            title: '审核通过',
            icon: 'none'
          })
          wx.hideLoading()
          that.upload()
        } else {
          wx.hideLoading()
          wx.showToast({
            title: '图片内容不符合审核要求',
            icon: 'none'
          })
        }
      }).catch(err => {
        // reslove(true)
        wx.hideLoading()
        console.log(err)
      })
    },
    fail: res => {
      wx.hideLoading();
      wx.showToast({
        title: "上传失败",
      })
    }
  })
}

function getLoginCode() {
  return new Promise((resolve, reject) => {
    wx.login({
      success: res => {
        // 这里也可以选择性返回需要的字段
        resolve(res.code)
      },
      fail(res) {
        reject(res);
      }
    })
  })
}

function checkLogin(showTip) {
  let flag = true
  flag = showTip ? false : true
  return new Promise((resolve, reject) => {
    let token = wx.getStorageSync('token');
    const loginTime = wx.getStorageSync('loginTime')
    let nowTime = Math.round(new Date());
    let expandTime = 29 * 24 * 60 * 60 * 1000
    let newTime = nowTime - loginTime
    if (!token) {
      wx.removeStorageSync('token')
      if (flag) {
        wx.showToast({
          title: '请先登录',
          icon: 'none'
        })
      }
      reject()
    } else {
      resolve()
    }
  })
}
const contactUrlParams = (o) => {
  let arr = [];
  Object.keys(o).forEach((key) => {
    arr.push(`${key}=${o[key]}`);
  });
  return "?" + arr.join("&");
}

function uploadStaticFile(filePath) {
  wx.showLoading({
    title: '上传中...',
    mask: true
  })
  let token = wx.getStorageSync('token');
  let header = {
    'Content-Type': 'multipart/form-data',
  };
  if (token) {
    header['Authorization'] = token
  }
  let suffix = /\.\w+$/.exec(filePath);
  return new Promise((resolve, reject) => {
    wx.uploadFile({
      url: uploadFileUrl,
      filePath: filePath,
      name: 'file',
      formData: {
        file: filePath
      },
      header: {
        'Content-Type': 'multipart/form-data'
      },
      success: function (res) {
        wx.hideLoading()
        if (res.statusCode === 200) {
          if (typeof res.data === "string") {
            const data = JSON.parse(res.data)
            if (data.code === 200) {
              resolve(data.data)
            }
          }
        }
      },
      complete: function (res) {
        wx.hideLoading()
      }
    })
  })

}
module.exports = {
  checkLogin,
  uploadImage,
  uploadStaticFile,
  checkContent,
  cutBase64,
  contactUrlParams,
  uploadPic,
  checkImg,
  getLoginCode
}